package com.cloud.logger.zchain.core;

import com.cloud.logger.zchain.core.common.properties.ServerInfo;
import com.cloud.logger.zchain.core.zookeeper.LeaderElection;
import com.cloud.logger.zchain.core.zookeeper.ZookeeperFactory;
import org.apache.zookeeper.KeeperException;
import org.quartz.*;
import org.quartz.impl.JobExecutionContextImpl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class JobDetailProxyBean implements Job {
    private String key;
    private String group;
    private String description;
    private String mode;
    private Object targetObject;
    private Method targetMethod;

    public String getKey() {
        return this.key;
    }

    public String getGroup() {
        return this.group;
    }

    public String getDescription() {
        return this.description;
    }

    public String getMode() {
        return this.mode;
    }

    public Object getTargetObject() {
        return this.targetObject;
    }

    public Method getTargetMethod() {
        return this.targetMethod;
    }

    public void setTargetObject(Object targetObject) {
        this.targetObject = targetObject;
    }

    public void setTargetMethod(Method targetMethod) {
        this.targetMethod = targetMethod;
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            //分布式负载均衡预留字段
            String className = targetObject.toString();
            String methodName = targetMethod.getName();
            String leader = LeaderElection.getLeader();
            if(leader!=null && leader.equals(ServerInfo.scheduleNode))
                this.targetMethod.invoke(this.targetObject, new Object[] {});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
